package cn.deepmax.spring.cloud.system.product.service.impl;


import cn.deepmax.spring.cloud.system.product.entity.Product;
import cn.deepmax.spring.cloud.system.product.entity.Product_;
import cn.deepmax.spring.cloud.system.product.repository.ProductRepository;
import cn.deepmax.spring.cloud.system.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.Optional;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepository productRepository;


    @Override
    public Optional<Product> findProduct(Long id) {
        Optional<Product> product = productRepository.findById(id);
        if(product.isPresent() && !product.get().getDelFlag()){
            return product;
        }else{
            return Optional.empty();
        }
    }

    @Override
    public Page<Product> findProductList(String name, Integer page,Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size, new Sort(Sort.Direction.DESC, "id"));
        if(StringUtils.isEmpty(name)){
            return productRepository.findAll(pageRequest);
        }else{
            return productRepository.findAll((root,query,cb)->{
                 Predicate condition = cb.like(root.get(Product_.name), "%" + name + "%");


                return condition;
            }, pageRequest);
        }
    }


}
